<template>
	<div>
		<section style="margin-bottom:15px">
			<el-button type="primary" @click="chooseDateDialogVisible = true">查看业务系统健康报告</el-button>
		</section>
		<VNodeTab :tableData="tableData" />
		<el-dialog title="选择时间" :visible.sync="dialogVisible" :close-on-press-escape="false"
			:close-on-click-modal="false" :show-close="false" @close="InitTime">
			<p style="margin-right:5px;display: inline;font-size:15px">开始日期:</p>
			<el-date-picker class="blockStart" v-model="postData.time" type="datetime" placeholder="开始日期"
				:picker-options="pickerOptions" :clearable="false" value-format="yyyy-MM-dd HH:mm:ss">
			</el-date-picker>
			<p style="margin:0 5px;display: inline;font-size:15px">结束日期:</p>
			<el-date-picker class="blockEnd" v-model="postData.time2" type="datetime" placeholder="结束日期"
				:picker-options="pickerOptions" :clearable="false" value-format="yyyy-MM-dd HH:mm:ss">
			</el-date-picker>
			<el-drawer title="业务系统健康报告" :visible.sync="drawerVisible" direction="rtl" size="100%" :show-close="true"
				:destroy-on-close="true" :wrapperClosable="false" :append-to-body="true" @close="drawerClose">
				<!-- <keep-alive> -->
				<section class="deawerBox">
					<section class="fwq_con">
						<div class="fwq_head">服务器状态</div>
						<div id="chartBox">
							<template v-for="[key, value] of Object.entries(ServerData)">
								<el-card class="box-card" style="margin-top:15px" :key="key">
									<div slot="header" class="clearfix">
										<span>{{ key }}详情</span>
									</div>
									<div>
										<VServerPerformance :itemData="value" />
									</div>
								</el-card>
							</template>
						</div>
					</section>
					<section class="otherCon">
						<div class="sjk_head">数据库状态</div>
						<div class="sjk_con">
							<template v-for="[key, value] of Object.entries(DataBaseData)">
								<el-card class="box-card" style="margin-top:15px" :key="key">
									<div slot="header" class="clearfix">
										<span>{{ key }}详情</span>
									</div>
									<div>
										<VDataBasePerformancefrom :itemData="value" />
									</div>
								</el-card>
							</template>
						</div>
					</section>
				</section>
				<!-- </keep-alive> -->
			</el-drawer>
			<div slot="footer" class="dialog-footer">
				<el-button :disabled="ButtonLoading" @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" :loading="ButtonLoading" @click="hangleClick">检索</el-button>
			</div>
		</el-dialog>
		<!-- 选择时间 -->
		<el-dialog title="选择时间" :visible.sync="chooseDateDialogVisible" width="30%">
			<template>
				<div class="block" style="width: 100%;display: flex;flex-direction: row;justify-content: center;">
					<el-date-picker v-model.lazy="chooseTime" :picker-options="expireTimeOPtion"
						value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至"
						start-placeholder="开始日期" end-placeholder="结束日期">
					</el-date-picker>
				</div>
			</template>
			<span slot="footer" class="dialog-footer">
				<el-button @click="chooseDateDialogVisible = false">取 消</el-button>
				<el-button type="primary" :loading="butLoading" @click="getReport()">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 丢包率时间选择 -->
		<el-dialog title="选择时间" :visible.sync="chooseDBDialogVisible" width="30%">
			<template>
				<div class="block" style="width: 100%;display: flex;flex-direction: row;justify-content: center;">
					<el-date-picker v-model="diubaoTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
						placeholder="选择日期时间" :picker-options="expireTimeOPtion">
					</el-date-picker>
				</div>
				<div
					style="font-size: 11px;color: red;width: 100%;display: flex;flex-direction: row;justify-content: center;">
					*查询输入时间前后一个小时的数据</div>
			</template>
			<span slot="footer" class="dialog-footer">
				<el-button @click="chooseDBDialogVisible = false">取 消</el-button>
				<el-button type="primary" :loading="DBLoading" @click="diubao()">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 丢包率 -->
		<el-dialog title="丢包率" :visible.sync="diuibaoDialogTableVisible">
			<el-table :data="gridData" style="width: 100%" height="500">
				<el-table-column fixed prop="ifname" label="ifname" width="150">
				</el-table-column>
				<el-table-column prop="inerrors" label="inerrors" width="120">
				</el-table-column>
				<el-table-column prop="inuti" label="inuti" width="120">
				</el-table-column>
				<el-table-column prop="phy" label="phy" width="120">
				</el-table-column>
				<el-table-column prop="protocol" label="protocol" width="100">
				</el-table-column>
				<el-table-column prop="recordTime" label="recordTime" width="200">
				</el-table-column>
				<el-table-column prop="resType" label="resType" width="150">
				</el-table-column>
				<el-table-column prop="sn" label="sn" width="150">
				</el-table-column>
			</el-table>
		</el-dialog>
		
		<el-drawer title="性能分析报告" :visible.sync="drawer" :direction="direction" size="100%" @close="drawerClose">
			<div class="reportBox">
				<el-row>
					<el-col :span="12">
						<div class="reportName">服务器状态</div>
						<div class="reLeftBox">
							<div style="width:95%;margin: 10px auto;background-color: white;"
								v-for="[key, value] of Object.entries(allData)">
								<div class="reportTitleBox">
									<div style="font-size: 18px;">（{{value.lable}}){{value.type}}{{key}}详情</div>
									<el-button v-show="value.type == 'Network'" type="primary" @click="chooseDB(key)">丢包率
									</el-button>
								</div>
								<ReportContent :allData="value" />
							</div>
						</div>
					</el-col>
					<el-col :span="12">
						<div class="reportName">数据库状态</div>
						<div class="reRightBox">
							<div class="sjk_con">
								<template v-for="[key, value] of Object.entries(DataBaseData)">
									<el-card class="box-card" :key="key">
										<div slot="header" class="clearfix">
											<span>{{ key }}详情</span>
										</div>
										<div>
											<VDataBasePerformancefrom :itemData="value" />
										</div>
									</el-card>
								</template>
							</div>
						</div>
					</el-col>
				</el-row>
			</div>
		</el-drawer>
	</div>
</template>

<script>
	import VNodeTab from "./NodeTab.vue";
	import moment from "moment";
	import {
		postJavaServerData
	} from "@/api";
	import VDataBasePerformancefrom from "./DataBasePerformance.vue";
	import VServerPerformance from './ServerPerformance.vue'
	import ReportContent from '../../management/components/ReportContent.vue'
	export default {
		components: {
			VNodeTab,
			ReportContent,
			VDataBasePerformancefrom,
			VServerPerformance
		},
		props: ["CountData", "SERVICESNAMEColumns", "BID"],
		data() {
			return {
				DataBaseItem: [],
				ServerItem: [],
				allData: {},
				tableData1:[],
				chooseIp: [],
				diubaoKey:'',
				tableData: [],
				direction: 'rtl',
				chooseDateDialogVisible:false,
				chooseDBDialogVisible:false,
				diuibaoDialogTableVisible:false,
				DBLoading:false,
				drawer:false,
				diubaoTime:'',
				gridData:[],
				butLoading: false,
				chooseTime: [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - 1, new Date()
					.getHours(), new Date().getMinutes(), new Date().getSeconds()), new Date()],
				expireTimeOPtion: {
					disabledDate(time) {
						return time.getTime() > Date.now() - 8.64e6; //如果没有后面的-8.64e6就是不可以选择今天的 
					}
				},
				areaType: {
					server: ["cpu", "memory", "network"],
					dataBase: ["back", "dbtime", "session", "io"],
				},
				drawerVisible: false,
				dialogVisible: false,
				//禁止选未来时间
				pickerOptions: {
					disabledDate: (time) => {
						return time.getTime() > Date.now();
					},
				},
				postData: {
					time: moment()
						.subtract(2, "days")
						.format("YYYY-MM-DD HH:mm:ss"),
					time2: moment().format("YYYY-MM-DD HH:mm:ss"),
					a: this.CountData["os"],
				},
				ButtonLoading: false,
				DataBaseData: {},
				ServerData: {}
			};
		},

		methods: {
			InitData() {
				if (this.CountData["DB"].length > 0) {
					this.DataBaseItem = this.CountData["DB"].map((_) => {
						return {
							IP: _.ip,
							SERVICESTYPE: _.systemname,
							PORT: _.port,
							ALERTLEVELCONFIG: _.alertLevelconfig,
							SERVICESNAME: this.SERVICESNAMEColumns[_.bid] || "",
							CREATEDATA: moment(_.createdate).format("YYYY-MM-DD HH:mm:ss"),
							CATEGORIES: _.dbtype,
						};
					});
				} else {
					this.DataBaseItem = [];
				}

				if (this.CountData["os"].length > 0) {
					this.ServerItem = this.CountData["os"].map((_) => {
						return {
							IP: _.ip,
							SERVICESTYPE: _.osType,
							PORT: _.port,
							ALERTLEVELCONFIG: _.alertLevelconfig,
							SERVICESNAME: this.SERVICESNAMEColumns[_.bid] || "",
							CREATEDATA: moment(_.createdate).format("YYYY-MM-DD HH:mm:ss"),
							CATEGORIES: _.osType,
						};
					});
				} else {
					this.ServerItem = [];
				}

				this.tableData = [...this.DataBaseItem, ...this.ServerItem];
					let db = this.CountData.DB
					let os = this.CountData.os
					if (db.length > 0) {
						db.forEach((item, index) => {
							this.tableData1.push(item)
						})
					}
					if (os.length > 0) {
						os.forEach((item, index) => {
							this.tableData1.push(item)
						})
					}
				console.log('table',this.tableData1)
			},
			InitTime() {
				this.postData.time = moment()
					.subtract(2, "days")
					.format("YYYY-MM-DD HH:mm:ss");
				this.postData.time2 = moment().format("YYYY-MM-DD HH:mm:ss");
			},
			async diubao() {
				this.DBLoading = true
				this.chooseIp = []
				console.log(this.tableData1)
				this.tableData1.forEach((item, index) => {
					console.log("表格", item)
					if (item.ip == this.diubaoKey) {
						this.chooseIp.push(item)
					}
				})
				console.log('时间',new Date(this.diubaoTime))
				let time = Date.parse(new Date(this.diubaoTime))
				console.log(time)
				let time1 = parseInt(time) - 3600000
				let time2 = parseInt(time) + 3600000
				// console.log(111,this.changeTime(time))
				// console.log(222,this.changeTime(time1))
				// console.log(333,this.changeTime(time2))
				const DB = {
					a: this.chooseIp,
					time: this.changeTime(time1),
					time2: this.changeTime(time2)
				};
				await postJavaServerData('/Sp/PacketlossRate', DB).then((res)=>{
					console.log("hid", res)
					if(res.data && res.data.length > 0){
						this.gridData = res.data
						this.diuibaoDialogTableVisible = true
						this.DBLoading = false
						this.chooseDBDialogVisible = false
					}else{
						this.gridData = []
						this.diuibaoDialogTableVisible = true
						this.DBLoading = false
						this.chooseDBDialogVisible = false
					}
				}).catch((err)=>{
					console.log(err)
					this.diuibaoDialogTableVisible = true
					this.DBLoading = false
					this.chooseDBDialogVisible = false
				})
			},
			changeTime(timestamp){
				let date = new Date(parseInt(timestamp));
				let Year = date.getFullYear();
				let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
				let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
				let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
				let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
				let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
				return Year + '-' + Moth + '-' + Day + ' ' + Hour + ':' + Minute + ':' + Sechond;
			},
			drawerClose() {
				this.drawer = false
			},
			chooseDB(key) {
				this.gridData = []
				this.diubaoKey = key
				this.chooseDBDialogVisible = true
			},
			async getReport() {
				this.butLoading = true
				console.log(1, this.chooseTime)
				console.log(2, this.CountData)
				let db = this.CountData.DB
				let os = this.CountData.os
				console.log('有什么', os)
				const _postServerData = {
					b: db,
					time: this.dateformars(this.chooseTime[0]),
					time2: this.dateformars(this.chooseTime[1])
				};
				const _postDataBaseData = {
					a: os,
					time: this.dateformars(this.chooseTime[0]),
					time2: this.dateformars(this.chooseTime[1])
				};
				let res1 = await postJavaServerData('/Sp/dbPerformance', _postServerData)
				console.log('db', res1)
				this.disposeDataForDataBase(res1)
				let res2 = await postJavaServerData('/Sp/osPerformance', _postDataBaseData)
				console.log('os', res2)
				this.allData = res2
				this.drawer = true
				this.butLoading = false
				this.chooseDateDialogVisible = false
			
			},
			dateformars(timestamp) {
				let time = new Date(timestamp)
				let year = time.getFullYear()
				let month = time.getMonth() + 1
				let date = time.getDate()
				let hours = time.getHours()
				let minute = time.getMinutes()
				let second = time.getSeconds()
			
				if (month < 10) {
					month = '0' + month
				}
				if (date < 10) {
					date = '0' + date
				}
				if (hours < 10) {
					hours = '0' + hours
				}
				if (minute < 10) {
					minute = '0' + minute
				}
				if (second < 10) {
					second = '0' + second
				}
				return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
			},
			hangleClick() {
				// console.log('啊?',this.CountData)
				this.ButtonLoading = true;
				const getPerformance = async () => {
					const _postServerData = {
						a: this.CountData["os"],
						time: this.postData.time,
						time2: this.postData.time2,
					};
					const _postDataBaseData = {
						b: this.CountData["DB"],
						time: this.postData.time,
						time2: this.postData.time2,
					};
					await postJavaServerData("/Sp/dbPerformance", {
							..._postDataBaseData
						})
						.then((r) => {
							this.disposeDataForDataBase(r);
						})
						.catch((e) => {
							this.$message.error("get database datas error");
						});
					await postJavaServerData("/Sp/osPerformance", {
							..._postServerData
						})
						.then((r) => {
							this.disposeDataForServer(r);
						})
						.catch((e) => {
							this.$message.error("get server datas error");
						});
				};
				getPerformance();
			},
			disposeDataForServer(data) {
				let AreaData = {},
					_index,
					_ip,
					_type;

				for (const [key, value] of Object.entries(data)) {
					_index = this.areaType.server.findIndex((item) => key.includes(item));
					if (_index !== -1) {
						_type = this.areaType.server[_index];
						_ip = key.replace(_type, "");
						if (!AreaData[_ip]) {
							AreaData[_ip] = [];
						}
						AreaData[_ip].push(
							...(value || []).map((item) => {
								return {
									country: _type,
									date: moment(item.recordTime).format("YYYY-MM-DD HH:mm:ss"),
									value: item.cpuIdle || 0,
								};
							})
						);
					}
				}
				this.ServerData = AreaData;
				console.log('这是？',this.ServerData)
				this.ButtonLoading = false;
				this.drawerVisible = true;
				// this.createChart(AreaData);
			},
			disposeDataForDataBase(data) {
				let AreaData = {},
					_index,
					_ip,
					_type;
				for (const [key, value] of Object.entries(data)) {
					_index = this.areaType.dataBase.findIndex((item) => key.includes(item));
					if (_index !== -1) {
						_type = this.areaType.dataBase[_index];
						_ip = key.replace(_type, "");
						if (!AreaData[_ip]) {
							AreaData[_ip] = {};
						}
						AreaData[_ip][_type] = value;
					}
				}
				this.DataBaseData = AreaData;
			},
			drawerClose() {
				this.drawerVisible = false;
				this.dialogVisible = false;
				this.DataBaseData = {};
			},
		},
		watch: {
			CountData: function(newval, oldval) {
				this.InitData();
			},
		},
	};
</script>

<style lang="scss" scope>
	#el-drawer__title {
		margin-bottom: 0 !important;
		padding: 20px 20px 10px !important;
	}
	.reportBox {
		height: 850px;
		background-color: gainsboro;
		border-radius: 10px;
	
	}
	
	.reRightBox {
		width: 100%;
		height: 800px;
		overflow: scroll;
		background-color: white;
	}
	
	.reportTitleBox {
		display: flex;
		flex-direction: row;
		width: 96%;
		justify-content: space-between;
		align-items: center;
		margin: 0 auto;
		padding: 10px;
	}
	
	.reLeftBox {
		background-color: white;
		border-radius: 3px;
		overflow: hidden;
		width: 99%;
		height: 800px;
		overflow: scroll;
	}
	
	.reportName {
		width: 98%;
		margin: 5px auto;
		font-size: 18px;
		text-align: center;
		color: cadetblue;
		font-weight: bold;
	}

	.el-drawer__open .el-drawer.rtl {
		padding: 0px 10px 5px;
	}
	
	.sjk_con {
		overflow-y: scroll;
		/* background-color: white; */
	}
	
	.sjk_con::-webkit-scrollbar {
		width: 3px;
		height: 3px;
	}
	
	.sjk_con::-webkit-scrollbar-thumb {
		border-radius: 3px;
	}

	.el-drawer__body {
		overflow: unset;
	}

	.deawerBox {
		display: grid;
		justify-content: center;
		grid-template-columns: 50% 50%;
		column-gap: 5px;
		row-gap: 5px;
		height: 100%;

		.otherCon {
			background: #dfdfdf;
			border-radius: 5px;
			height: 100%;
			padding: 5px 10px;

			.sjk_head {
				color: #0d477e;
				font-size: 15px;
				display: grid;
				justify-items: center;
				font-weight: 600;
			}

			.sjk_con {
				height: 92vh;
				overflow-y: scroll;
			}

			.sjk_con::-webkit-scrollbar {
				width: 3px;
				height: 3px;
			}

			.sjk_con::-webkit-scrollbar-thumb {
				// background-color: rgb(209, 201, 201);
				border-radius: 3px;
			}
		}

		.fwq_con {
			background: #dfdfdf;
			border-radius: 5px;
			height: 100%;

			.fwq_head {
				color: #0d477e;
				font-size: 15px;
				display: grid;
				justify-items: center;
				font-weight: 600;
			}

			#chartBox {
				display: flex;
				flex-direction: row;
				flex-flow: wrap;
				overflow-y: scroll;
				height: 92vh;
			}

			@media screen and (max-width: 1900px) {
				#chartBox {
					justify-content: start;
				}

				#chartBox>div {
					width: 380px;
				}
			}

			@media screen and (max-width: 1648px) {
				#chartBox {
					justify-content: center;
				}

				#chartBox>div {
					width: 80%;
				}
			}

			@media screen and (min-width: 1900px) {
				#chartBox {
					justify-content: start;
				}

				#chartBox>div {
					width: 440px;
				}
			}

			#chartBox::-webkit-scrollbar {
				width: 3px;
				height: 3px;
			}

			#chartBox::-webkit-scrollbar-thumb {
				border-radius: 3px;
			}

			#chartBox>div {
				background: white;
				margin: 5px;
				padding: 5px;
			}
		}
	}
</style>
